<template>
  <div class="common-container" style="min-height: calc(100vh - 60px)">
    <!-- 订单状态筛选 -->
    <div class="common-content">
      <div class="order-filter">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="全部订单" name="all"></el-tab-pane>
          <el-tab-pane label="待支付" name="pending"></el-tab-pane>
          <el-tab-pane label="待发货" name="processing"></el-tab-pane>
          <el-tab-pane label="待收货" name="shipped"></el-tab-pane>
          <el-tab-pane label="已完成" name="completed"></el-tab-pane>
          <el-tab-pane label="已取消" name="canceled"></el-tab-pane>
        </el-tabs>
      </div>
      
      <!-- 订单列表 -->
      <div class="order-list">
        <div v-for="order in orderList" :key="order.id" class="order-item">
          <!-- 订单头部 -->
          <div class="order-header">
            <div class="header-left">
              <span class="order-no">订单编号: {{ order.orderNo }}</span>
              <span class="order-time">创建时间: {{ formatDate(order.createTime) }}</span>
            </div>
            <div class="header-right">
              <span class="order-status" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</span>
            </div>
          </div>
          
          <!-- 订单商品 -->
          <div class="order-products">
            <div 
              v-for="item in order.orderItems" 
              :key="item.id"
              class="product-item"
              @click="viewGoodsDetail(item.productId)"
            >
              <img :src="item.productImg" alt="" class="product-img">
              <div class="product-info">
                <div class="product-name">{{ item.productName }}</div>
                <div class="product-price">¥{{ item.price }}</div>
                <div class="product-quantity">x{{ item.quantity }}</div>
              </div>
            </div>
          </div>
          
          <!-- 订单金额 -->
          <div class="order-amount">
            <span>共 {{ order.orderItems.length }} 件商品，合计: <span class="total-price">¥{{ order.totalPrice.toFixed(2) }}</span></span>
          </div>
          
          <!-- 订单操作 -->
          <div class="order-actions">
            <div v-if="order.status === 1"> <!-- 待支付 -->
              <el-button @click="goToPayment(order.id, order.totalPrice)" type="primary" size="small">去支付</el-button>
              <el-button @click="cancelOrder(order.id)" size="small">取消订单</el-button>
            </div>
            <div v-else-if="order.status === 2"> <!-- 待发货 -->
              <el-button disabled size="small">待发货</el-button>
            </div>
            <div v-else-if="order.status === 3"> <!-- 待收货 -->
              <el-button @click="confirmReceipt(order.id)" type="primary" size="small">确认收货</el-button>
            </div>
            <div v-else-if="order.status === 4"> <!-- 已完成 -->
              <el-button @click="goToComment(order.id)" size="small">评价商品</el-button>
              <el-button @click="buyAgain(order)" size="small">再次购买</el-button>
            </div>
            <div v-else> <!-- 已取消或其他状态 -->
              <el-button disabled size="small">已完成</el-button>
            </div>
            <el-button @click="viewOrderDetail(order.id)" type="text" size="small">查看详情</el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    
    <!-- 空状态 -->
    <div v-if="orderList.length === 0 && !loading" class="empty-state">
      <el-empty description="暂无订单记录"></el-empty>
      <el-button type="primary" @click="goToGoodsList" style="margin-top: 20px">
          去购物
        </el-button>
    </div>
    
    <!-- 加载中 -->
    <div v-loading="loading" class="loading-container" element-loading-text="加载中..."></div>
  </div>
</template>

<script>
export default {
  name: "OrderList",
  data() {
    return {
      orderList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      activeTab: 'all',
      loading: false
    };
  },
  created() {
    this.loadOrderList();
  },
  watch: {
    activeTab() {
      this.currentPage = 1;
      this.loadOrderList();
    }
  },
  methods: {
    loadOrderList() {
      this.loading = true;
      
      // 根据选中的标签获取对应的状态值
      let status = '';
      if (this.activeTab === 'pending') status = '待付款';
      else if (this.activeTab === 'processing') status = '待发货';
      else if (this.activeTab === 'shipped') status = '待收货';
      else if (this.activeTab === 'completed') status = '已完成';
      else if (this.activeTab === 'canceled') status = '已关闭';
      
      this.request.get("/orders/page", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: status
        }
      }).then(res => {
        this.loading = false;
        
        if (res.code === 200 && res.data && res.data.records) {
          // 字段映射，适配前端展示
          this.orderList = res.data.records.map(order => ({
            ...order,
            id: order.id,
            orderNo: order.no || order.orderNo,
            status: this.getStatusNumber(order.status), // 将状态字符串转换为数字
            orderItems: order.details ? order.details.map(item => ({
              id: item.id,
              productId: item.goodsId || item.productId,
              productName: item.goodsName || item.productName,
              productImg: item.imgUrl || item.img || item.productImg,
              price: item.price,
              quantity: item.num || item.quantity
            })) : [],
            totalPrice: order.total
          }));
          this.total = res.data.total || 0;
        } else {
          this.$message.error(res.msg || '获取订单列表失败');
        }
      }).catch(() => {
        this.loading = false;
        this.$message.error('获取订单列表失败');
      });
    },
    
    getStatusNumber(statusText) {
      const statusMap = {
        '已关闭': 0,
        '待付款': 1,
        '待发货': 2,
        '待收货': 3,
        '已完成': 4
      };
      return statusMap[statusText] !== undefined ? statusMap[statusText] : statusText;
    },
    
    getStatusText(status) {
      const statusMap = {
        0: '已取消',
        1: '待支付',
        2: '待发货',
        3: '待收货',
        4: '已完成',
        5: '已退款'
      };
      return statusMap[status] || '未知状态';
    },
    
    getStatusClass(status) {
      const statusClassMap = {
        0: 'status-canceled',
        1: 'status-pending',
        2: 'status-processing',
        3: 'status-shipped',
        4: 'status-completed',
        5: 'status-refunded'
      };
      return statusClassMap[status] || '';
    },
    
    viewOrderDetail(orderId) {
      this.$router.push(`/front/orderDetail?orderId=${orderId}`);
    },
    
    viewGoodsDetail(productId) {
      this.$router.push(`/front/goodsDetail/${productId}`);
    },
    
    goToPayment(orderId, amount) {
      this.$router.push({
        path: '/front/payment',
        query: {
          orderId: orderId,
          amount: amount
        }
      });
    },
    
    cancelOrder(orderId) {
      this.$confirm('确定要取消该订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.put(`/orders/${orderId}/status`, { status: '已关闭' }).then(res => {
          if (res.code === 200) {
            this.$message.success('订单已取消');
            this.loadOrderList();
          } else {
            this.$message.error(res.msg || '取消订单失败');
          }
        }).catch(() => {
          this.$message.error('取消订单失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    confirmReceipt(orderId) {
      this.$confirm('确认已收到商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.request.put(`/orders/${orderId}/status`, { status: '已完成' }).then(res => {
          if (res.code === 200) {
            this.$message.success('确认收货成功');
            this.loadOrderList();
          } else {
            this.$message.error(res.msg || '确认收货失败');
          }
        }).catch(() => {
          this.$message.error('确认收货失败');
        });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    goToComment(orderId) {
      this.$router.push({
        path: '/front/comment',
        query: {
          orderId: orderId
        }
      });
    },
    
    buyAgain(order) {
      // 将订单中的商品添加到购物车
      // 由于管理端没有批量添加购物车的API，我们为每个商品单独添加
      const addPromises = order.orderItems.map(item => {
        return this.request.post("/cart", {
          goodsId: item.productId,
          num: item.quantity
        });
      });
      
      Promise.all(addPromises).then(results => {
        const failedResults = results.filter(res => res.code !== 200);
        if (failedResults.length === 0) {
          this.$message.success('已添加到购物车');
          this.$router.push('/front/cart');
        } else {
          this.$message.error('部分商品添加购物车失败');
        }
      }).catch(() => {
        this.$message.error('添加购物车失败');
      });
    },
    
    goToGoodsList() {
      this.$router.push('/front/goodsList');
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.loadOrderList();
    },
    
    handleCurrentChange(current) {
      this.currentPage = current;
      this.loadOrderList();
    },
    
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    }
  }
};
</script>

<style scoped>
.common-container {
  padding: 0;
}

.common-content {
  margin-bottom: 20px;
}

.order-filter {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 10px 0;
}

.order-list {
  margin-bottom: 20px;
}

.order-item {
  background-color: #fff;
  margin-bottom: 20px;
  padding: 20px;
  border-radius: 4px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.order-no,
.order-time {
  color: #606266;
  font-size: 14px;
  margin-right: 20px;
}

.order-status {
  font-weight: bold;
  padding: 5px 10px;
  border-radius: 4px;
}

/* 不同状态的样式 */
.status-pending {
  color: #1890ff;
  background-color: #e6f7ff;
}

.status-processing {
  color: #fa8c16;
  background-color: #fff7e6;
}

.status-shipped {
  color: #52c41a;
  background-color: #f6ffed;
}

.status-completed {
  color: #52c41a;
  background-color: #f6ffed;
}

.status-canceled {
  color: #8c8c8c;
  background-color: #f5f5f5;
}

.status-refunded {
  color: #ff4d4f;
  background-color: #fff1f0;
}

.order-products {
  margin-bottom: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 20px;
}

.product-info {
  flex: 1;
}

.product-name {
  color: #303133;
  margin-bottom: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 5px;
}

.product-quantity {
  color: #909399;
  font-size: 14px;
}

.order-amount {
  text-align: right;
  margin-bottom: 15px;
  color: #606266;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
  background-color: #fff;
  border-radius: 4px;
}

.loading-container {
  background-color: #fff;
  padding: 40px;
  text-align: center;
}
</style>